<template>
  <el-container>
    <el-aside width="10%"></el-aside>
    <el-main style="width: 80%;">
      <el-row :gutter="25">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div style="display: flex;justify-content: center;">
                <el-image
                    :src="userinfo.avatarurl"
                    :fit="'fill'"
                />
              </div>
            </template>
            <div style="display: flex;justify-content: center;">
              <span>{{userinfo.username}}</span>
            </div>

<!--            <template #footer>-->
<!--              <div style="display: flex;justify-content: center;">-->
<!--                <el-button type="primary" round>更换头像</el-button>-->
<!--              </div>-->
<!--            </template>-->
          </el-card>
        </el-col>
        <el-col :span="18">
          <div>
            <el-tabs type="border-card" v-model="activeName">
              <el-tab-pane label="用户信息" name="User">
                <span style="font-size: 25px;">个人信息</span>
                <el-divider />
                <el-form ref="formRef2" :model="userinfo" label-position="left" label-width="auto" :rules="rules1" status-icon>
                  <el-form-item label="账号" prop="username">
                    <el-input v-model="userinfo.username" disabled/>
                  </el-form-item>
                  <el-form-item label="用户名" prop="nickname">
                    <el-input v-model="userinfo.nickname"/>
                  </el-form-item>
                  <el-form-item label="个性签名" prop="signature">
                    <el-input v-model="userinfo.signature"
                              type="textarea"
                              :rows="3"
                              :maxlength="150"
                    />
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userinfo.email"/>
                  </el-form-item>
                  <div style="display: flex;justify-content: center;">
                    <el-button type="success" @click="submitForm1">更新信息</el-button>
                  </div>
                </el-form>
              </el-tab-pane>


              <el-tab-pane label="修改密码" name="Modify">
                <span style="font-size: 25px;">密码修改</span>
                <el-divider />
                <el-form ref="formRef" :model="passwordmodify" label-position="left" label-width="auto" :rules="rules2" status-icon>
                  <el-form-item label="旧密码" prop="old_pwd">
                    <el-input type="password" v-model="passwordmodify.old_pwd"/>
                  </el-form-item>
                  <el-form-item label="新密码" prop="new_pwd">
                    <el-input type="password" v-model="passwordmodify.new_pwd"/>
                  </el-form-item>
                  <el-form-item label="确认密码" prop="re_pwd">
                    <el-input type="password" v-model="passwordmodify.re_pwd"/>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="success" @click="submitForm2">修改密码</el-button>
                  </el-form-item>
                </el-form>

              </el-tab-pane>
              <el-tab-pane label="用户头像" name="Avatar">
                <div
                    v-loading="loading"
                    element-loading-text="Loading..."
                    :element-loading-spinner="svg"
                    element-loading-svg-view-box="-10, -10, 50, 50"
                >
                  <el-upload
                      ref="uploadRef"
                      class="avatar-uploader"
                      action="/api/upload"
                      :show-file-list="false"
                      name="file"
                      :headers="{'Authorization':tokenStore.token}"
                      :on-success="uploadSuccess"
                      :before-upload="beforeUpload"

                  >
                    <el-image v-if="imgAvatarUrl" :src="imgAvatarUrl" class="avatar" :fit="'fill'" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                  <br />
                  <el-button type="primary" :icon="Plus" size="large"  @click="uploadRef.$el.querySelector('input').click()"
                  >
                    选择图片
                  </el-button>
                  <el-button type="success" :icon="Upload" size="large" @click="updateAvatar">
                    上传头像
                  </el-button>
                </div>

                <p>1. 先点击"选择图片"或"+"图标,上传文件</p>
                <p>2. 点击"上传头像",完成修改</p>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
      </el-row>
    </el-main>
    <el-aside width="10%"></el-aside>
  </el-container>

</template>

<script setup>
import {ref} from "vue"
import {ElMessage, ElMessageBox} from "element-plus";
import {userInfoUpdateService,userPwdUpdateService,userAvatarUpdateService} from '/src/api/User.js'
import useUserInfoStore from '/src/stores/userInfo.js'
import {useTokenStore} from '/src/stores/token.js'
import { Plus, Upload } from '@element-plus/icons-vue'

import { ElForm } from 'element-plus';
import {deleteCommentService} from "../../api/Admin.js";



const activeName = ref('User')

//获取token
const tokenStore = useTokenStore();
//获取用户信息
const userInfoStore = useUserInfoStore();

const userinfo = ref({...userInfoStore.info})

const passwordmodify = ref({
  old_pwd:'',
  new_pwd:'',
  re_pwd:''
})

const userinfomodify = ref({
  nickname:'',
  signature:'',
  email:''
})

//加载数据等待遮罩
const loading = ref(true)

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>`


//修改密码表单
const formRef = ref(null);
//个人信息表单
const formRef2 = ref(null)

//校验密码的函数
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value !== passwordmodify.value.new_pwd) {
    callback(new Error('请确保两次输入的密码一样'))
  } else {
    callback()
  }
}

//定义个人信息表单校验规则
const rules1 = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  signature: [
    { required: true, message: '请输入个性签名', trigger: 'blur' },
    { min: 1, max: 150, message: '长度为1~150位非空字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
  ]
}


//定义修改密码表单校验规则
const rules2 = {
  old_pwd: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    // { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    // { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  re_pwd: [
    { validator: checkRePassword, trigger: 'blur' }
  ]
}

// 修改个人信息表单提交
const submitForm1 = () => {
  formRef2.value.validate((valid) => {
    if (valid) {
      // 通过验证，执行提交操作
      // ElMessage.success('验证成功')
      // 在这里发出请求
      // 修改个人信息
      updateUserInfo()

    } else {
      ElMessage.error("验证失败")
      return false;

    }
  });
};

//修改密码表单提交
const submitForm2 = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 通过验证，执行提交操作
      // ElMessage.success('验证成功')
      // 在这里发出请求
      // 修改密码
      updatePwd()
     } else {
      ElMessage.error("验证失败")
      return false;
    }
  });
};

//修改密码
const updatePwd = async() => {

  // if(passwordmodify.value.old_pwd === '' || passwordmodify.value.new_pwd === '' || passwordmodify.value.re_pwd === ''){
  //   ElMessage.error("请填写完整")
  //   return
  // }
  // if(passwordmodify.value.new_pwd !== passwordmodify.value.re_pwd){
  //   ElMessage.error("请确保两次输入的密码一样")
  //   return
  // }

  let result = await userPwdUpdateService(passwordmodify.value)
  ElMessage.success(result.message ? result.message : '修改成功')
  //1.清空pinia中存储的token以及个人信息

  tokenStore.removeToken()
  userInfoStore.removeInfo()

  //2.跳转到登录页面
  router.push('/login')

}

//修改个人信息
const updateUserInfo = async () =>{
  userinfomodify.value.nickname = userinfo.value.nickname
  userinfomodify.value.signature = userinfo.value.signature
  userinfomodify.value.email = userinfo.value.email
  let result = await userInfoUpdateService(userinfomodify.value)
  ElMessage.success(result.message ? result.message : '修改成功')
  //userInfoStore.setInfo(userinfo)

}

//用户头像地址
const imgAvatarUrl = ref(userinfo.value.avatarurl)

loading.value = false

const uploadRef = ref()

// 上传文件前判断图片大小是否一致
const beforeUpload =(file) =>{

  loading.value = true

  const isJPG =
      file.type === 'image/jpeg' ||
      'image/jpg' ||
      'image/gif' ||
      'image/png';
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isJPG) {
    ElMessage.error(
        '上传头像图片只能是 JPG、JPEG、GIF或PNG 格式!'
    );
    loading.value = false
    return
  }
  if (!isLt5M) {
    ElMessage.error('上传头像图片大小不能超过 5MB!');
    loading.value = false
    return
  }
  // 上传图片前处理函数
  const isSize = new Promise(function(resolve, reject) {
    // let width = 600;
    // let height = 480;
    let _URL = window.URL || window.webkitURL;
    let image = new Image();
    image.onload = function() {
      let valid = image.width === image.height;
      valid ? resolve() : reject();
    };
    image.src = _URL.createObjectURL(file);
  }).then(
      () => {
        return file;
      },
      () => {
        ElMessage.error("上传图片尺寸不符合,宽高必须一致");
        loading.value = false
        return Promise.reject();
      }
  );

  return isJPG && isLt5M && isSize;
}


//图片上传成功的回调函数
const uploadSuccess = (result)=>{

  imgAvatarUrl.value = result.data;
  loading.value = false
}

//头像修改
const updateAvatar = ()=>{

  ElMessageBox.confirm(
      '您确定要上传这个头像吗?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        //调用接口
        let result = await userAvatarUpdateService(imgAvatarUrl.value);

        ElMessage.success(result.message? result.message:'修改成功')

        //修改pinia中的数据
        userInfoStore.info.avatarurl = imgAvatarUrl.value
        //左侧显示头像区域更改值
        userinfo.value.avatarurl = imgAvatarUrl.value

      })
      .catch(() => {
        ElMessage.warning('取消删除!')
      })




}

</script>





<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>